package com.example.administrator.text;

import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.AgentIp;
import util.AndroidJSInterface;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.Url;
import util.payUtil.PayUtil;

/**
 * 时长充值
 */
public class TimeRechargeActivity extends BaseActivity {
    private String mMoney;
    private WebView mWebView;
    private double mUnitPrice = 0.1;
    private String mVip = "";
    private String mId,mToken;
    private boolean mState = true;
    private Logger mLogger = Logger.getLogger(HomeUtil.class);
    public Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                mTVRecharg.setText("充值");
            }
        }
    };

    @Bind(R.id.activity_timerecharge_fl)           FrameLayout mFrameLoayout;
    @Bind(R.id.activity_timerecharge_tv)           TextView mTextView;
    @Bind(R.id.activity_timerecharge_tv_recharg)   TextView mTVRecharg;
    @Bind(R.id.activity_timerecharge_tv_money1)    TextView mTVMoney1;
    @Bind(R.id.activity_timerecharge_tv_money2)    TextView mTVMoney2;
    @Bind(R.id.activity_timerecharge_tv_money5)    TextView mTVMoney5;
    @Bind(R.id.activity_timerecharge_tv_money10)   TextView mTVMoney10;
    @Bind(R.id.activity_timerecharge_tv_time1)     TextView mTVTime1;
    @Bind(R.id.activity_timerecharge_tv_time2)     TextView mTVTime2;
    @Bind(R.id.activity_timerecharge_tv_time5)     TextView mTVTime5;
    @Bind(R.id.activity_timerecharge_tv_time10)    TextView mTVTime10;
    @Bind(R.id.activity_timerecharge_ll1)          LinearLayout mLL1;
    @Bind(R.id.activity_timerecharge_ll2)          LinearLayout mLL2;
    @Bind(R.id.activity_timerecharge_ll3)          LinearLayout mLL3;
    @Bind(R.id.activity_timerecharge_ll4)          LinearLayout mLL4;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_recharge);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        init();
    }

    private void init(){
        mVip = (int)SharedPreferencesUtils.getParam(this,HomeUtil.mVIPCombonum,1)+"";
        HomeUtil.getHemeUtilNew().getStatusBar(this, mFrameLoayout);
        mId = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mUseridDB,"");
        mToken = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mTokenDB, "");
        queryMoney();
        HomeUtil.getHemeUtilNew().saveCombo(this,0,null);
    }

    @OnClick(R.id.activity_timerecharge_ll1)
    void ll1(){
       mTVMoney1.setTextColor(ContextCompat.getColor(this,R.color.Land_true));
       mTVMoney2.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
       mTVMoney5.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
       mTVMoney10.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
       mTVTime1.setTextColor(ContextCompat.getColor(this,R.color.Land_true));
       mTVTime2.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
       mTVTime5.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
       mTVTime10.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
       mMoney = (int)(10*mUnitPrice)+"";
       mTextView.setText("¥"+mMoney);
       mLL1.setBackgroundResource(R.drawable.activity_timerecharge_ll_true);
       mLL2.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
       mLL3.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
       mLL4.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
    }

    @OnClick(R.id.activity_timerecharge_ll2)
    void ll2(){
        mTVMoney1.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVMoney2.setTextColor(ContextCompat.getColor(this,R.color.Land_true));
        mTVMoney5.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVMoney10.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVTime1.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mTVTime2.setTextColor(ContextCompat.getColor(this,R.color.Land_true));
        mTVTime5.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mTVTime10.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mMoney = (int)(20*mUnitPrice)+"";
        mTextView.setText("¥"+mMoney);
        mLL1.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL2.setBackgroundResource(R.drawable.activity_timerecharge_ll_true);
        mLL3.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL4.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
    }

    @OnClick(R.id.activity_timerecharge_ll3)
    void ll3(){
        mTVMoney1.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVMoney2.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVMoney5.setTextColor(ContextCompat.getColor(this,R.color.Land_true));
        mTVMoney10.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVTime1.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mTVTime2.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mTVTime5.setTextColor(ContextCompat.getColor(this,R.color.Land_true));
        mTVTime10.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mMoney = (int)(50*mUnitPrice)+"";
        mTextView.setText("¥"+mMoney);
        mLL1.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL2.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL3.setBackgroundResource(R.drawable.activity_timerecharge_ll_true);
        mLL4.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
    }

    @OnClick(R.id.activity_timerecharge_ll4)
    void ll4(){
        mTVMoney1.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVMoney2.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVMoney5.setTextColor(ContextCompat.getColor(this,R.color.binding_gray));
        mTVMoney10.setTextColor(ContextCompat.getColor(this,R.color.Land_true));
        mTVTime1.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mTVTime2.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mTVTime5.setTextColor(ContextCompat.getColor(this,R.color.home_viewpage_text));
        mTVTime10.setTextColor(ContextCompat.getColor(this,R.color.Land_true));
        mMoney = (int)(100*mUnitPrice)+"";
        mTextView.setText("¥"+mMoney);
        mLL1.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL2.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL3.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL4.setBackgroundResource(R.drawable.activity_timerecharge_ll_true);
    }

    /**
     * 返回
     */
    @OnClick(R.id.activity_timerecharge_ll)
    void getFinish(){
        LogUtil.eE("finish","........."+Url.getUrlNew().getNETWORKING_ATATE());
        if(Url.getUrlNew().getNETWORKING_ATATE() == 1){
            NetWorkstateUtil.getInstance().getBrokenNetwork(this,null,1);
            Url.getUrlNew().setIsonResumeJudge(false);
            finish();
            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Url.getUrlNew().setIsonResumeJudge(true);
                }
            },1500);
        }else {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogUtil.eE("","...........onKeyDown..............");
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(Url.getUrlNew().getNETWORKING_ATATE() == 1){
                NetWorkstateUtil.getInstance().getBrokenNetwork(this,null,1);
                Url.getUrlNew().setIsonResumeJudge(false);
                HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Url.getUrlNew().setIsonResumeJudge(true);
                    }
                },1500);
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 充值
     */
    @OnClick(R.id.activity_timerecharge_tv_recharg)
    void recharg(){
        LogUtil.eE("",".........recharg.........mTime.."+"....mState.."+mState);
        mLogger.info("充值..recharg()..mTime"+mMoney+"....mState.."+mState);
            if(mState){
                mState = false;
                mTVRecharg.setText("请求中...");
                AgentIp.newInstance(this).setNetWorkstate2(new AgentIp.OnNetworkStateClickListener() {
                    @Override
                    public void onClick(boolean state) {
                        if(state){
                            Url.getUrlNew().setNETWORKING_ATATE(0);
                            order();
                        }else {
                            NetWorkstateUtil.getInstance().showNetworking(TimeRechargeActivity.this, new NetWorkstateUtil.NetworkingOnClickListener() {
                                @Override
                                public void onItemClick(boolean state) {
                                    if(state){
                                        Url.getUrlNew().setNETWORKING_ATATE(1);
                                        order();
                                    }else {
                                        mState = true;
                                        mTVRecharg.setText("充值");
                                        Toast.makeText(TimeRechargeActivity.this,"放行互联网失败,可以连接移动网络充值",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    }
                });
            }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//取消注册
    }

    /**
     * 生成订单
     */
    private void order(){
        mLogger.info("充值..order()..加载网页");
        SharedPreferencesUtils.setParam(this, PayUtil.PAY_COMMODITY,"时长充值");
        mWebView = new WebView(this);
        mWebView.loadUrl(Url.mATIAIRIP+Url.getUrlNew().BALANCE);
        mWebView.getSettings().setJavaScriptEnabled(true);           //设置WebView属性，能够执行Javascript脚本
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);  //支持通过JS打开新窗口
        mWebView.getSettings().setLoadWithOverviewMode(true);                  // 缩放至屏幕的大小
        mWebView.getSettings().setLoadsImagesAutomatically(true);             //支持自动加载图片
        mWebView.getSettings().setBuiltInZoomControls(true);                 //启用内置缩放装置
        mWebView.getSettings().setDisplayZoomControls(false);               //隐藏webview缩放按钮
        AndroidJSInterface ajsi = new AndroidJSInterface(this);
        mWebView.addJavascriptInterface(ajsi,ajsi.getInterface());
        mWebView.setWebViewClient(new WebViewClient() {
            @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
               /* Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                */
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view,url);

                   mVip = (int)SharedPreferencesUtils.getParam(TimeRechargeActivity.this,HomeUtil.mVIPCombonum,1)+"";
                   if(mId.equals("") || mVip.equals("0") || mMoney.equals("")){
                           getToast("请求参数有误，可重试");
                           HomeUtil.getHemeUtilNew().getCoupon(TimeRechargeActivity.this,null);
                           mId = (String) SharedPreferencesUtils.getParam(TimeRechargeActivity.this,HomeUtil.mUseridDB,"");
                           queryMoney();
                   }else {
                       String string = "javascript:calljs(" +"'"+ mId +"',"+ "'"+ mVip +"',"+"'"+mMoney+"',"+"'"+MyApplication.getApp().getmPattern()+"',"+"'"+MyApplication.getApp().getSiteAreaid()+"'"+")";
                       mLogger.info("充值..order()..调用网页的calljs()方法..生成订单..string.."+string);
                       mWebView.loadUrl(string);
                   }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 接受所有网站的证书
                // super.onReceivedSslError(view, handler, error);
            }
        });

    }

    /**
     * 查询 价格
     */
    private void queryMoney(){
        HashMap map = new HashMap<>();
        LogUtil.eE("","......mVip....."+mVip);
        mVip = (int) SharedPreferencesUtils.getParam(this, HomeUtil.mVIPCombonum,1)+"";
        map.put("vipid",mVip);
        map.put("model_id",MyApplication.getApp().getmPattern());
        mLogger.info("queryMoney()...url.."+Url.mATIAIRIP+Url.getUrlNew().Time_Money+"......mVip.."+mVip);
        GreenTreeNetworkUtil.getInstance().doPost(this,Url.mATIAIRIP+Url.getUrlNew().Time_Money,1,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                mLogger.info("queryMoney()...onSuccess.."+response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject jsonArray = jsonObject.getJSONObject("memberinfo");
                        mUnitPrice = Double.parseDouble(jsonArray.getString("internet_price"));
                        mMoney = (int)(10*mUnitPrice)+"";
                        setView();

                } catch (JSONException e) {
                    e.printStackTrace();
                    wifi();
                }
            }

            @Override public void onFailure(Throwable onFailure) {
                mLogger.info("queryMoney()...onFailure.."+onFailure.toString());
                wifi();
            }
        });
    }

    private void setView(){
        mTVMoney1.setText("¥"+(int)(10*mUnitPrice)+"元");
        mTVMoney2.setText("¥"+(int)(20*mUnitPrice)+"元");
        mTVMoney5.setText("¥"+(int)(50*mUnitPrice)+"元");
        mTVMoney10.setText("¥"+(int)(100*mUnitPrice)+"元");
        mTextView.setText("¥"+(int)(10*mUnitPrice)+"元");
        mTextView.setText("¥"+mMoney);
    }

    /*** 订阅事件FirstEvent*/
    @Subscribe
    public void onEventMainThread(String string){
        LogUtil.eE("","..onEventMainThread..."+string);
        if(string != null && string.equals("finish")){
            finish();
        }else if(string != null && string.equals("state")){
            mState = true;
            mHandler.sendEmptyMessageDelayed(1,0);
        }
    }

    private void showRl(){
        mTVMoney1.setTextColor(getResources().getColor(R.color.binding_gray));
        mTVMoney2.setTextColor(getResources().getColor(R.color.binding_gray));
        mTVMoney5.setTextColor(getResources().getColor(R.color.binding_gray));
        mTVTime1.setTextColor(getResources().getColor(R.color.home_viewpage_text));
        mTVTime2.setTextColor(getResources().getColor(R.color.home_viewpage_text));
        mTVTime5.setTextColor(getResources().getColor(R.color.home_viewpage_text));
        mLL1.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL2.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
        mLL3.setBackgroundResource(R.drawable.activity_timerecharge_ll_false);
    }

    private void wifi(){
        mMoney = "1";
        setView();
    }
}
